package com.starsoft.smdc.crawler.danjuan;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.starsoft.frame.fileimport.JsonReader;
import com.starsoft.frame.fileimport.pojo.Column;
import com.starsoft.frame.fileimport.pojo.DataTable;
import com.starsoft.frame.fileimport.pojo.NullType;
import com.starsoft.frame.fileimport.pojo.Table;
import com.starsoft.frame.fileimport.pojo.Table.TitleType;
import com.starsoft.frame.fileimport.pojo.ValueType;
import com.starsoft.frame.util.DateUtil;
import com.starsoft.frame.util.MapUtil;
import com.starsoft.frame.util.StringUtil;
import com.starsoft.smdc.bean.SmdcMarketDaily;
import com.starsoft.smdc.bean.SmdcSecurity;
import com.starsoft.smdc.crawler.common.CrawlerService;
import com.starsoft.smdc.crawler.common.MarketDailyCrawler;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

@Component
public class MarketDailyDanjuan extends CrawlerService implements MarketDailyCrawler {

	private static Logger logger = LoggerFactory.getLogger(MarketDailyDanjuan.class);

	public MarketDailyDanjuan() {
		this.apiMap = new HashMap<>();
		apiMap.put("indexPeHistory", "https://danjuanfunds.com/djapi/index_eva/pe_history/%s?day=%s");
		apiMap.put("indexPbHistory", "https://danjuanfunds.com/djapi/index_eva/pb_history/%s?day=%s");
		apiMap.put("fullEarningIndex", "https://www.csindex.com.cn/csindex-home/perf/index-perf?indexCode=%s&startDate=%s&endDate=%s");
		apiMap.put("indexPeHistory2", "https://www.etfshare.cn/api/v1.0/get_index_figures_series_value?IndexCode=%s&chartdataname=PE_add_weight_his");
		apiMap.put("indexPbHistory2", "https://www.etfshare.cn/api/v1.0/get_index_figures_series_value?IndexCode=%s&chartdataname=PB_add_weight_his");
		
	}
	
	@Override
	public List<SmdcMarketDaily> update(SmdcSecurity security, Date begin) {
		return update(Arrays.asList(security), Arrays.asList(begin));
	}

	@Override
	public List<SmdcMarketDaily> update(List<SmdcSecurity> securityList, List<Date> begin) {
		List<SmdcMarketDaily> result = new ArrayList<SmdcMarketDaily>();
		for (int i = 0; i < securityList.size(); i++) {
			SmdcSecurity security = securityList.get(i);
			try {
				List<SmdcMarketDaily> markets = getIndexValuation(security, begin.get(i));
				result.addAll(markets);
				marketDailyDao.saveOrUpdateBatch(markets);
			} catch (Exception e) {
				logger.error("", e);
			}
		}
		return result;
	}
	
	private List<SmdcMarketDaily> getIndexValuation(SmdcSecurity security, Date begin) {
		List<SmdcMarketDaily> markets = new ArrayList<>();
		if (security.getCrawleValuation() == null || !security.getCrawleValuation()) {
			return markets;
		}
		long count = DateUtil.getDays(begin, new Date());
		if (count < 0) {
			return markets;
		}

		Map<Date, SmdcMarketDaily> marketMap = marketDailyDao.getAfter(security.getSecId(), begin).stream()
				.collect(Collectors.toMap(a -> a.getId().getTradeDate(), a -> a));

		String secId = security.getTicker();
		String peResponse = this.request("indexPeHistory2", secId);

		JSONObject peJson = (JSONObject) JSONUtil.parse(peResponse);
		JSONArray date = peJson.getJSONArray("date");
		JSONArray data = peJson.getJSONArray("PE_add_weight_his");
		for (int i = 0; i < date.size(); i++) {
			Date tradeDate = DateUtil.toDate(date.get(i).toString(), "yyyy-MM-dd");
			SmdcMarketDaily market = marketMap.get(tradeDate);
			if (market != null) {
				market.setPeWeighted(data.get(i, Double.class));
				markets.add(market);
			}
		}

		String pbResponse = this.request("indexPbHistory2", secId);
		JSONObject pbJson = (JSONObject) JSONUtil.parse(pbResponse);
		JSONArray datePb = pbJson.getJSONArray("date");
		JSONArray dataPb = pbJson.getJSONArray("PB_add_weight_his");
		for (int i = 0; i < datePb.size(); i++) {
			Date tradeDate = DateUtil.toDate(datePb.get(i).toString(), "yyyy-MM-dd");
			SmdcMarketDaily market = marketMap.get(tradeDate);
			if (market != null) {
				market.setPbWeighted(dataPb.get(i, Double.class));
				if (market.getPeWeighted() != null && market.getPeWeighted() != null) {
					market.setRoeWeighted(market.getPbWeighted() / market.getPeWeighted());
				}
				markets.add(market);
			}
		}

		return markets;
	}
	
	protected String convertSecId(String secId, boolean isToLocal) {
		if (isToLocal) {
			String ticker = secId.substring(2);
			String exchange = secId.substring(0, 2);
			exchange = flexsetService.codeConvertFrom(SMDC_EXCHANGE, exchange, this.getTargetSystem());
			return ticker + "." + exchange;
		} else {
			int index = secId.indexOf(".");
			String ticker = secId.substring(0, index);
			String exchange = secId.substring(index + 1);
			exchange = flexsetService.codeConvertTo(SMDC_EXCHANGE, exchange, this.getTargetSystem());
			return exchange + ticker;
		}
	}

	@Override
	protected String getTargetSystem() {
		return "xueqiu";
	}

}
